package com.example.demo.controller;

import com.example.demo.pojo.User;
import com.example.demo.service.Impl.LoginServiceImpl;
import com.example.demo.service.Impl.UserServiceImpl;
import com.example.demo.util.Unite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Map;


@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    LoginServiceImpl loginService;

    @Autowired
    UserServiceImpl userService;

    @GetMapping ("{username}/{password}")
    public Unite login(@PathVariable String username, @PathVariable String password, HttpServletRequest request){
        Integer login = loginService.login(username, password);
        HttpSession session=request.getSession();
        Unite unite;
        if(login==-1){
            unite=new Unite(login,false);
        }else{
            User user=userService.getUserById(login);
            if(user.getState().equals("lock")){
                if(user.getLastTime().before(new Timestamp(System.currentTimeMillis()))){
                    user.setState("off");
                    userService.updateById(user);
                }
            }
            session.setAttribute("user",login);
            unite=new Unite(login,true);
        }

        return unite;
    }
    @PostMapping
    public Unite register(@RequestBody User user){
        //System.out.println(user);

        userService.insertUser(user);

        return null;
    }
    @GetMapping("/check")
    public Unite check(@RequestParam String username){
        System.out.println(username);
        Unite unite;
        if(loginService.checkUsername(username))
            unite=new Unite(null,true);
        else{
            unite=new Unite(null,false);
        }
        return unite;
    }
    @GetMapping("/rootLogin")
    public Unite rootLogin(@RequestParam String username,@RequestParam String pwd){
        if("root".equals(username)&&"123456".equals(pwd)){
            return new Unite(null,true);
        }
        return new Unite(null,false);

    }

}
